﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using Microsoft.SharePoint;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Support.Constants;
using Office = Microsoft.Office.DocumentManagement.DocumentSets;
using MS.InformationManagement.Support.Enums;

namespace MS.InformationManagement.BLL.ReceivedDocuments
{
    public class UpdatePrintedToReceivedStatusCommand : IBaseCommand
    {

        #region Fields

        IList<int> _selectedItems;

        #endregion

        #region Constructors

        public UpdatePrintedToReceivedStatusCommand(IList<int> selectedItems)
        {
            _selectedItems = selectedItems;
        }

        #endregion

        #region Command Methods

        public void Execute()
        {
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                var selectedEntities = Support.GetPrintedEntities(dc, _selectedItems);
                ChangeRadicadoStatus(selectedEntities);
            }
        }

        public void Undo()
        {
            //TODO:Undo changes in selected radicados
        }

        #endregion

        #region Private Methods
         
        private void ChangeRadicadoStatus(IEnumerable<DocumentoImpreso> selectedEntities)
        { 

            string currentUser = SPContext.Current.Web.CurrentUser.LoginName;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {
                        currentSite.AllowUnsafeUpdates = true;
                        currentWeb.AllowUnsafeUpdates = true;
                        foreach (var entity in selectedEntities)
                        {
                            SPListItem currentItem = currentWeb.Lists[entity.BibliotecaDelDocumento].GetItemById(Convert.ToInt16(entity.IdDocumento.Value));
                            Office.DocumentSet selectedDocument = Office.DocumentSet.GetDocumentSet(currentItem.Folder);
                            selectedDocument.Folder.Item[CustomSiteColumns.FIELD_DOCUMENT_STATUS_WINDOW] = true;
                            selectedDocument.Log(string.Empty, DateTime.Now, TraceableOperation.Ventanilla, string.Empty, string.Empty);
                            selectedDocument.Folder.Item.SystemUpdate();
                            selectedDocument.Folder.Update();
                        }
                        currentWeb.AllowUnsafeUpdates = false;
                        currentSite.AllowUnsafeUpdates = false;
                    }
                }
            });         
        }

        #endregion


    }
}
